package com.czl.module_service.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.viewpager.widget.PagerAdapter
import com.alibaba.android.arouter.launcher.ARouter
import com.czl.base.binding.command.BindingCommand
import com.czl.base.binding.command.BindingConsumer
import com.czl.module_service.bean.MenuItemModel
import com.czl.module_service.databinding.ItemStorehouseBinding
import com.czl.module_service.fragment.StoreManageFragment

/**
 * @author by xubin,
 * @date on 2022/1/18.
 * PS: Not easy to write code, please indicate.
 */
class MultiplePagerAdapter(
    private val fragment: StoreManageFragment,
    private val mList: List<MenuItemModel>?
) : PagerAdapter() {

    override fun getCount(): Int {
        return mList?.size ?: 0
    }

    override fun isViewFromObject(view: View, o: Any): Boolean {
        val binding: ViewDataBinding = o as ViewDataBinding
        return view == binding.root
    }

    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
        super.destroyItem(container, position, `object`)
        val binding: ViewDataBinding = `object` as ViewDataBinding
        container.removeView(binding.root)
    }

    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        val binding = ItemStorehouseBinding.inflate(
            LayoutInflater.from(fragment.requireContext()),
            container,
            true
        )
        binding.apply {
            data = mList!![position]
            adapter = this@MultiplePagerAdapter
        }
        return binding
    }

    val onItemClick: BindingCommand<Any> = BindingCommand(BindingConsumer {
        if (it is MenuItemModel) {
            if (it.container) {
                fragment.startContainerActivity(
                    it.routePath
                )
            } else {
                ARouter.getInstance().build(it.routePath).navigation()
            }
        }

    })

    override fun getPageWidth(position: Int): Float {
        return 0.25f
    }
}